package com.alipay.util;

import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;

import java.io.IOException;


/**
 * @author Jun
 */
public class JsonUtil {
    /**
     * mapper created as static singleton
     */
    public final static ObjectMapper MAPPER = new ObjectMapper();

    static {
        MAPPER.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
        MAPPER.configure(DeserializationFeature.FAIL_ON_INVALID_SUBTYPE, false);
        MAPPER.setSerializationInclusion(JsonInclude.Include.NON_NULL);
    }

    /**
     * obj 转 json string
     * 若 object 为 null，则返回值为 "null" 的字符串
     */
    public static String toJson(Object object) {
        try {
            return JsonUtil.MAPPER.writeValueAsString(object);
        } catch (JsonProcessingException e) {
            throw new RuntimeException(e.getMessage());
        }
    }

    /**
     * json string 转 obj
     * 若 json string 为 null, 则抛出 NPE
     */
    public static <T> T fromJson(String json, Class<T> classOfT) {
        try {
            return JsonUtil.MAPPER.readValue(json, classOfT);
        } catch (IOException e) {
            throw new RuntimeException(e.getMessage());
        }
    }

    /**
     * json string 转 obj
     * 若 json string 为 null, 则抛出 NPE
     */
    public static <T> T fromJson(String json, TypeReference<T> toValueTypeRef) {
        try {
            return JsonUtil.MAPPER.readValue(json, toValueTypeRef);
        } catch (IOException e) {
            throw new RuntimeException(e.getMessage());
        }
    }
}